#!/bin/sh

count=$(iptables -n -L INPUT 2>/dev/null | grep -c "V2RAY-SERVER")
if [ -n "$count" ]; then
	until [ "$count" = 0 ]
	do
		rules=$(iptables -n -L INPUT --line-num 2>/dev/null | grep "V2RAY-SERVER" | awk '{print $1}')
		for rule in $rules
		do
			iptables -D INPUT $rule 2>/dev/null
			break
		done
		count=$(expr $count - 1)
	done
fi

iptables -F V2RAY-SERVER 2>/dev/null && iptables -X V2RAY-SERVER 2>/dev/null

enable=$(uci -q get v2ray_server.@global[0].enable)
if [ $enable -eq 1 ]; then
	iptables -N V2RAY-SERVER
	iptables -I INPUT -j V2RAY-SERVER
	
	count=$(uci show v2ray_server | grep "@user" | sed -n '$p' | cut -d '[' -f 2 | cut -d ']' -f 1)
	[ -n "$count" ] && [ "$count" -ge 0 ] && {
		u_get() {
			local ret=$(uci -q get v2ray_server.@user[$1].$2)
			echo ${ret:=$3}
		}
		for i in $(seq 0 $count); do
			enable=$(u_get $i enable 0)
			[ $enable -eq 0 ] && continue
			remarks=$(u_get $i remarks)
			bind_local=$(u_get $i bind_local)
			port=$(u_get $i port)
			[ "$bind_local" != "1" ] && {
				iptables -A V2RAY-SERVER -p tcp --dport $port -m comment --comment "$remarks" -j ACCEPT
				iptables -A V2RAY-SERVER -p udp --dport $port -m comment --comment "$remarks" -j ACCEPT
			}
		done
	}
fi
